<template>
  <el-dialog :title="!dataForm.id ? '新建' : '编辑'" :close-on-click-modal="false"
    :visible.sync="visible" class="JNPF-dialog JNPF-dialog_center" lock-scroll width="600px"
    append-to-body @close="handleClose">
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" v-loading="formLoading"
      label-width="100px">
      <el-form-item label="名称" prop="fullName">
        <el-input v-model="dataForm.fullName" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="编码" prop="enCode">
        <el-input v-model="dataForm.enCode" placeholder="请输入编码" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="dataForm.category" placeholder="请选择分类" clearable filterable>
          <el-option v-for="(item,index) in categoryList" :label="item.fullName" :value="item.id"
            :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="前辍" prop="prefix">
        <el-input v-model="dataForm.prefix" placeholder="请输入前缀" @keyup.native="handleChange" />
      </el-form-item>
      <el-form-item label="方式" prop="type">
        <el-select v-model="dataForm.type" @change="handleTypeChange">
          <el-option label="时间格式" :value="1" />
          <el-option label="随机数编号" :value="2" />
          <el-option label="UUID" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label=" " prop="dateFormat" v-if="this.dataForm.type==1">
        <jnpf-select v-model="dataForm.dateFormat" :options="dateFormatList" :props="props"
          :clearable="false" @change="handleChange" />
      </el-form-item>
      <el-form-item label="位数" prop="digit" v-if="this.dataForm.type==1">
        <el-input v-model.number="dataForm.digit" maxlength="1" placeholder="请输入位数"
          @keyup.native="handleChange" />
      </el-form-item>
      <el-form-item label="位数" prop="randomDigit" v-if="this.dataForm.type==2">
        <el-select v-model="dataForm.randomDigit">
          <el-option label="16" :value="16" />
          <el-option label="32" :value="32" />
        </el-select>
      </el-form-item>
      <el-form-item label="起始值" prop="startNumber" v-if="this.dataForm.type==1">
        <el-input v-model="dataForm.startNumber" placeholder="不允许输入0或特殊字符"
          @keyup.native="handleChange" />
      </el-form-item>
      <el-form-item label="类型" prop="randomType" v-if="this.dataForm.type==2">
        <el-select v-model="dataForm.randomType">
          <el-option label="纯数字" :value="1" />
          <el-option label="字母+数字" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="后辍" prop="suffix">
        <el-input v-model="dataForm.suffix" placeholder="请输入后辍" @keyup.native="handleChange" />
      </el-form-item>
      <el-form-item label="范例" prop="example" v-if="this.dataForm.type==1">
        <el-input v-model="dataForm.example" disabled />
      </el-form-item>
      <el-form-item label="排序" prop="sortCode">
        <el-input-number :min="0" :max="999999" v-model="dataForm.sortCode"
          controls-position="right" />
      </el-form-item>
      <el-form-item label="状态" prop="enabledMark">
        <el-switch v-model="dataForm.enabledMark" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input v-model="dataForm.description" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.cancelButton')}}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="dataFormSubmit()">
        {{$t('common.confirmButton')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getBillRuleInfo,
  createBillRule,
  updateBillRule
} from '@/api/system/billRule'
import dayjs from 'dayjs'

export default {
  data() {
    var validateZero = (rule, value, callback) => {
      if (value || value === 0 || value === false) {
        let str = value.replace(/0/g, '')
        if (!str) callback(new Error(`起始值不能为${value}`));
        callback()
      }
    };
    return {
      visible: false,
      formLoading: false,
      btnLoading: false,
      dataForm: {
        fullName: '',
        enCode: '',
        prefix: '',
        digit: '',
        startNumber: '',
        example: '',
        sortCode: 0,
        enabledMark: 1,
        description: '',
        category: '',
        type: 1,
        dateFormat: 'YYYY',
        randomType: 1,
        randomDigit: 16,
        suffix: '',
      },
      categoryList: [],
      dataRule: {
        fullName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称最多为50个字符！', trigger: 'blur' }
        ],
        enCode: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { max: 50, message: '编码最多为50个字符！', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' },
        ],
        digit: [
          { required: true, message: '请输入位数', trigger: 'blur' },
          { type: 'number', message: '仅能输入正整数' },
          { pattern: /^[1-9]\d*$/, message: '仅能输入正整数' }
        ],
        startNumber: [
          { required: true, message: '请输入起始值', trigger: 'blur' },
          { pattern: /^[0-9]*$/, message: '只能输入数字', trigger: 'blur' },
          { validator: validateZero }
        ]
      },
      props: {
        label: "fullName",
        value: "id"
      },
      dateFormatList: [
        { fullName: 'YYYY', id: 'YYYY' },
        { fullName: 'YYYYMM', id: 'YYYYMM' },
        { fullName: 'YYYYMMDD', id: 'YYYYMMDD' },
        { fullName: 'YYYYMMDDHH', id: 'YYYYMMDDHH' },
        { fullName: 'YYYYMMDDHHmm', id: 'YYYYMMDDHHmm' },
        { fullName: 'YYYYMMDDHHmmss', id: 'YYYYMMDDHHmmss' },
        { fullName: 'YYYYMMDDHHmmssSSS', id: 'YYYYMMDDHHmmssSSS' },
        { fullName: 'no', id: 'no' },
      ]
    }
  },
  methods: {
    init(id, categoryList) {
      this.dataForm.id = id || ''
      this.categoryList = categoryList
      this.visible = true
      this.formLoading = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          getBillRuleInfo(this.dataForm.id).then(res => {
            this.dataForm = res.data
            this.formLoading = false
          }).catch(() => {
            this.formLoading = false
          })
        } else {
          this.formLoading = false
          this.handleChange()
        }
      })
    },
    handleTypeChange() {
      this.$refs['dataForm'].clearValidate(['digit', 'startNumber'])
      this.handleChange()
    },
    handleChange() {
      if (this.dataForm.type != 1) return
      // 流水前缀
      const prefix = this.dataForm.prefix || ''
      const suffix = this.dataForm.suffix || ''

      // 流水日期格式
      const dateFormat = this.dataForm.dateFormat
      let dateVal = ''
      if (dateFormat && dateFormat !== 'no') dateVal = dayjs().format(dateFormat)
      // 流水位数
      let digitVal = this.dataForm.digit
      if (digitVal != "") digitVal = Array(digitVal > 0 ? (digitVal - ('' + 0).length + 1) : 0).join('0') + 0

      // 流水起始
      const startNumber = this.dataForm.startNumber
      let startNumberVal = ''
      if (startNumber != "") {
        startNumberVal = (digitVal + startNumber)
        digitVal = startNumberVal.substring(startNumberVal.length - digitVal.length, startNumberVal.length)
        this.dataForm.startNumber = digitVal
      }
      // 流水范例
      this.dataForm.example = prefix + dateVal + digitVal + suffix
    },
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          const formMethod = this.dataForm.id ? updateBillRule : createBillRule
          formMethod(this.dataForm).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.btnLoading = false
                this.$emit('refreshDataList')
              }
            })
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>
